# -*- coding: utf-8 -*-

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <icatalan@opendomo.com>



from elisa.plugins.poblesec.link import Link
from elisa.core.common import application
from elisa.core.media_uri import MediaUri
from elisa.core.components.model import Model
from elisa.core.utils import defer
from elisa.core.utils.cancellable_defer import CancelledError
from elisa.core.utils.i18n import install_translation
from elisa.plugins.database.actions import PlayVideoAction
from elisa.plugins.poblesec.widgets.player.status_display import BARS 


from elisa.plugins.poblesec.base.hierarchy import HierarchyController
from elisa.plugins.poblesec.base.list import GenericListViewMode
from elisa.plugins.poblesec.base.preview_list import MenuItemPreviewListController
from elisa.plugins.poblesec.base.coverflow import ImageWithReflectionCoverflowController
from elisa.plugins.poblesec.base.grid import GridItemGridController
from elisa.plugins.poblesec.base.list_switcher import ListSwitcherController
from elisa.plugins.poblesec.actions import Action
from elisa.plugins.base.models.media import PlayableModel
from elisa.plugins.base.models.image import ImageModel
from elisa.plugins.base.utils import get_and_cache_image
from elisa.plugins.base.models.video import VideoModel
#from elisa.plugins.base.models.media import PlaylistModel

from elisa.plugins.opendomo.models import OpendomoResponseModel, OpendomoPhotoModel, FileModel

from elisa.plugins.opendomo.actions import LoginAction, LogoutAction, AccessAction
from elisa.plugins.opendomo import opendomo_api as opendomo
from elisa.plugins.opendomo.utils import get_opendomo_provider
from elisa.plugins.poblesec.sections_menu import main_menu_decorate
import os
_ = install_translation('opendomo')
_p = install_translation('poblesec')


class OpendomoEntryPointModel(Model):
    """ Model representing one of the main Opendomo menus.

    @ivar title:     menu title
    @type title:     unicode
    @ivar uri:       entry point URI
    @type uri:       L{elisa.core.media_uri.MediaUri}
    @ivar need_grid: should the entry point be browsed using the grid or not
    @type need_grid: bool
    """

    def __init__(self):
        super(Model, self).__init__()
        self.title = None
        self.uri = None
        self.need_grid = False

def opendomo_decorator_main(controller):
    link = Link()
    link.controller_path = '/poblesec/opendomo/access'
    link.label = _('Opendomo Access')
    controller.model.append(link)
    return defer.succeed(None)

def opendomo_decorator(controller):
    controller.append_plugin('opendomo', _('Opendomo'), '/poblesec/opendomo/access')
    return defer.succeed(None)


class ControllerMixin(object):

    empty_label = _('There is no content to show')

    def decorate(klass, controller):
        decorator = klass(controller)
        return decorator.initialize()

    def play_image(self, item):
        controllers = self.frontend.retrieve_controllers('/poblesec/slideshow_player')
        slideshow_controller = controllers[0]
        playlist = []
        index = 0

        # Cancel all currently queued requests
        for widget in self.nodes._widgets:
            self.cancel_deferreds(widget)

        for od_photo in self.model:
            if opendomo.isImage(od_photo.uri):
               uri_tmp = od_photo.uri.replace('&GUI=XML','').replace('&GUI=none','') 
               uri_item_ = item.references[0].path +'?'+ item.references[0].get_params_string()
               uri_item = uri_item_.replace('&GUI=XML','').replace('&GUI=none','') 
               if uri_tmp == uri_item:
                  # save the index of the image to be displayed first
                  index = len(playlist)
               image = ImageModel()       
               uri = MediaUri('http://'+opendomo.AGENT_IP+od_photo.uri)
               
               image.references.append(uri)
               image.title = od_photo.title
               image.can_rotate = False
               playlist.append(image)   
               
        slideshow_controller.player.set_playlist(playlist, index)
        controllers = self.frontend.retrieve_controllers('/poblesec')
        main = controllers[0]
        main.show_slideshow_player()
        return defer.succeed(None)
        
    def play_video(self, item):
            # play video
            controllers = self.frontend.retrieve_controllers('/poblesec/video_player')
            player = controllers[0]
            pbc = player.player_osd.status.status_display_details.progress_bars 
            player.player_osd.hide()            

            player.player.play_model(item)
            
            controllers = self.frontend.retrieve_controllers('/poblesec')
            main = controllers[0]
            main.show_video_player()
            return defer.succeed(None)
       
    def item_activated(self, item):    
        if opendomo.isImage(item.uri):
            image = ImageModel()       
            uri = MediaUri(opendomo.getTokenizedUrl('http://'+opendomo.AGENT_IP+item.uri))
            image.references.append(uri)
            image.title = item.title
            image.can_rotate = False

            dfr = self.play_image(image)
            
        elif opendomo.isCamera(item.uri):
            video = PlayableModel()       
            port = item.uri.split(':')[2].replace('?'+opendomo.XML_TAIL,'')
            uri = MediaUri('http://'+opendomo.AGENT_IP+'/cgi-bin/od.cgi?resource=cam001&resourceip='+opendomo.AGENT_IP+'&resourceport='+port+'&FRMMULT=40&'+opendomo.get_cached_token())
            video.uri = uri
            video.title = item.title

            dfr = self.play_video(video)  
     
        elif opendomo.isVideo(item.uri):
            video = PlayableModel()       
            uri = MediaUri(opendomo.getTokenizedUrl('http://'+opendomo.AGENT_IP+item.uri))
            video.uri = uri
            video.title = item.title
            
            dfr = self.play_video(video)        
                
        else:
            controllers = self.frontend.retrieve_controllers('/poblesec/browser')
            browser = controllers[0]
           
            """ Aqui se hacen los mapeos a las URLs de los actions en el CGI"""
            if item.type == opendomo.MENU_ITEM:
                path = '/poblesec/opendomo/access'
            if item.type == opendomo.COMMAND:
                path = '/poblesec/opendomo/access'

            if "browseCaptures" in item.uri or "browseFiles" in item.uri or "cameraShow" in item.uri:
                OpendomoListSwitcherPreviewController.default_mode = OpendomoGridController
            else:
                OpendomoListSwitcherPreviewController.default_mode = OpendomoPreviewListController            
 
            if item.type == opendomo.COMMAND:
               dfr = browser.history.append_controller(path, item.title, uri=item.uri)                              
               opendomo.message_box(self,"Action result","The following action: "+item.title+" has been executed")                           
               dfr = browser.history.go_back()
            else:
               dfr = browser.history.append_controller(path, item.title, uri=item.uri)                              

        return dfr

    def create_actions(self):
        """
        The list can optionally have one default action and several contextual
        actions. Actions apply to all the items.
        Actions are activated when the user clicks on the item itself, and
        contextual actions are activated when the user clicks on the contextual
        action icons on the side of the item.

        You return from this method a tuple where the first item is the default
        action (or None if none), and the second item is a list of the
        contextual actions (or an empty list if none).
        """
        default_action = PlayVideoAction(self)
        contextual_actions = []
        return (default_action, contextual_actions)


class OpendomoController(ControllerMixin, HierarchyController):

    start_uri = opendomo.getTokenizedUrl(opendomo.URL_ROOT)
   
    def initialize(self, uri=start_uri):
        print '----URI----'
        print uri
        print '-----------'
        deferred = super(OpendomoController, self).initialize()
        def add_entries(result):
            provider = get_opendomo_provider()
            entries = provider.getEntries(uri)
        
            entry_models = []
            for title, need_grid, url, type in entries:
                entry_model = OpendomoEntryPointModel()
                if opendomo.isVideo(url):
                   entry_model.title = "[Video] "+title
                elif opendomo.isImage(url):
                   entry_model.title = "[Image] "+title                   
                else:
                   entry_model.title = title
                entry_model.uri = opendomo.getTokenizedUrl(url)
                entry_model.need_grid = need_grid
                entry_model.type = type
                if opendomo.isDir(url) or opendomo.isImage(url) or opendomo.isVideo(url) or opendomo.isScript(url):
                   entry_models.append(entry_model)

            self.model.extend(entry_models)
            """ TODO: Maybe add a Logout link? """
            #self.model.append(AccessAction(self))
            return self

        deferred.addCallback(add_entries)

        return deferred


class OpendomoViewMode(GenericListViewMode):

    """
    Implementation of the common view modes API.
    """

    def get_label(self, item):
        title = item.title
        return defer.succeed(title)

    def get_default_image(self, item):
        return 'elisa.plugins.poblesec.glyphs.small.pictures'

    def get_image(self, item, theme):

         if opendomo.isImage(item.uri):
            thumbnail_file = "/tmp/"+item.title
            uri = MediaUri(opendomo.getTokenizedUrl('http://'+opendomo.AGENT_IP+item.uri))

            def got_thumbnail(data_model):
                fd = file(thumbnail_file, 'wb')
                fd.write(data_model.data)
                fd.close()
                return thumbnail_file

            provider = get_opendomo_provider()
            data_model, thumbnail_deferred = provider.get(uri)
            return thumbnail_deferred.addCallback(got_thumbnail)
         elif opendomo.isVideo(item.uri):
            thumbnail_file_ = os.getenv("HOME")+"/.moovida/od_imgs/od_video.png"
            thumbnail_file = "/tmp/"+item.title
            index_f = item.uri.find("FILE")
            index_d = item.uri.find(".", index_f)
            index_a = item.uri.find("&", index_f)
            old_img_uri = item.uri[index_f:index_a]
            new_img_uri = item.uri[index_f:index_d]+".jpg"
            img_uri = item.uri.replace(old_img_uri,new_img_uri)
            print 'NEW IMG URI:'+img_uri
            uri = MediaUri(opendomo.getTokenizedUrl('http://'+opendomo.AGENT_IP+img_uri))

            def got_thumbnail(data_model):
                fd = file(thumbnail_file, 'wb')
                fd.write(data_model.data)
                fd.close()
                return thumbnail_file

            provider = get_opendomo_provider()
            data_model, thumbnail_deferred = provider.get(uri)
            #thumbnail_deferred.addErrback(thumbnail_file_)
            return thumbnail_deferred.addCallback(got_thumbnail)
         elif opendomo.isCamera(item.uri):
            thumbnail_file_ = os.getenv("HOME")+"/.moovida/od_imgs/od_video.png"
            if os.path.exists(thumbnail_file_):
                return defer.succeed(thumbnail_file_)
            else:
                return None
         elif opendomo.isDir(item.uri):
            thumbnail_file_f = os.getenv("HOME")+"/.moovida/od_imgs/folder.png"
            if os.path.exists(thumbnail_file_f):
                return defer.succeed(thumbnail_file_f)
            else:
                return None                
         else:       
              return None

class OpendomoPreviewListController(OpendomoController, MenuItemPreviewListController):
    view_mode = OpendomoViewMode
    # TODO: Activate to show nice images next to the menu
    item_widget_kwargs = {'with_artwork_box': False}

class OpendomoCoverflowController(OpendomoController, ImageWithReflectionCoverflowController):
    view_mode = OpendomoViewMode


class OpendomoGridController(OpendomoController, GridItemGridController):
    view_mode = OpendomoViewMode


class OpendomoListSwitcherController(ListSwitcherController):
    modes = [OpendomoPreviewListController,
             OpendomoCoverflowController,
             OpendomoGridController]
    crumbs_logo = "elisa.plugins.opendomo.crumbs_logo"
    default_mode = OpendomoGridController

class OpendomoListSwitcherPreviewController(OpendomoListSwitcherController):
    default_mode = OpendomoPreviewListController

def use_me_hook(frontend):
    """
    'Use me' hook that takes the user to the Pictures/Internet/Opendomo section.

    @param frontend: the current frontend (poblesec)
    @type frontend:  L{elisa.plugins.pigment.pigment_frontend.PigmentFrontend}

    @return:         a deferred fired when the action is complete
    @rtype:          L{elisa.core.utils.defer.Deferred}
    """
    browser = frontend.retrieve_controllers('/poblesec/browser')[0]
    paths = [('/poblesec/plugins_menu', _p('Plugins'), {}),
             ('/poblesec/opendomo/access', _('Opendomo'), {})]
    return browser.navigate(paths)

